<template>
  <div
    class="app-container"
    v-loading="loading"
  >
    <div style="padding:20px;background:#fff">
      <el-descriptions title="基础信息">
        <el-descriptions-item label="订单编号">{{detail.orderNo}}</el-descriptions-item>
        <el-descriptions-item label="用户昵称">{{detail.userNickName}}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{detail.userPhone}}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          {{detail.status === 0? '待支付' : 
          detail.status === 1? '待发货' : 
          detail.status === 2? '待收货' : 
           detail.status === 3? '待评价':
           detail.status === 4? '已评价':
           detail.status === 5? '售后中':
           detail.status === 6? '已关闭':
           detail.status === 7? '已取消':''}}
        </el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ detail.payType == 1 ? '微信支付' : detail.payType == 2 ? '微信+积分支付' : '未支付'  }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{detail.createTime}}</el-descriptions-item>
        <el-descriptions-item label="商品总价">{{detail.totalPrice}}</el-descriptions-item>
        <el-descriptions-item label="实付款">{{detail.realPayRmb}}</el-descriptions-item>
        <el-descriptions-item label="购买方式">{{detail.purchaseType == 1?'定金':'全款'}}</el-descriptions-item>
        <el-descriptions-item
          label="定金取值方式"
          v-if="detail.purchaseType == 1"
        >{{detail.depositPercentage}}（{{detail.depositValue}}元）</el-descriptions-item>

        <el-descriptions-item label="订单备注">{{detail.userRemark}}</el-descriptions-item>
      </el-descriptions>
    </div>
    <div style="padding:20px;background:#fff;margin:20px 0">
      <el-descriptions
        title="收货信息"
        style="margin:20px 0"
        :column="2"
      >
        <el-descriptions-item label="收货人姓名">{{detail.consigneeName}}</el-descriptions-item>
        <el-descriptions-item label="收货人手机号">{{detail.consigneePhone}}</el-descriptions-item>
        <el-descriptions-item
          span="2"
          label="收货地址"
        >{{detail.consigneeAddress}}</el-descriptions-item>
      </el-descriptions>
    </div>
    <div style="padding:20px;background:#fff;">
      <div style="font-weight:bold;margin:20px 0">商品信息</div>
      <el-table
        :data="tableData"
        style="width: 100%;text-align:center"
        :header-cell-style="{ 'text-align': 'center', 'background-color': '#f2f2f2' }"
        :cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column
          fixed
          prop="goodsName"
          label="商品名称"
          width="150"
        >
        </el-table-column>
        <el-table-column
          prop="goodsSpecificationsName"
          label="商品规格"
          width="120"
        >
        </el-table-column>
        <el-table-column
          prop="platformPrice"
          label="价格（元）"
          width="120"
        >
        </el-table-column>
        <el-table-column
          prop="crossedPrice"
          label="指导价（元）"
          width="120"
        >
        </el-table-column>
        <el-table-column
          prop="goodsNum"
          label="单价&数量"
          width="120"
        >
        </el-table-column>
        <el-table-column
          prop="freightRmb"
          label="运费（元）"
          width="120"
        >
        </el-table-column>
        <el-table-column
          prop="logisticsName"
          label="物流公司"
          width="120"
        >
        </el-table-column>
        <el-table-column
          prop="logisticsNo"
          label="物流单号"
          width="200"
        >
        </el-table-column>
        <el-table-column
          label="操作"
          width="120"
        >

          <template slot-scope="scope">
            <el-button
              @click="click().handleShipments(scope.row)"
              type="text"
              size="small"
              v-if="detail.status == 1"
            >发货</el-button>

            <el-button
              @click="click().handleExpress(scope.row)"
              type="text"
              size="small"
              v-if="detail.status == 2 || detail.status == 3"
            >查看物流</el-button>

            <el-button
              type="text"
              size="small"
              @click="click().handleRefund(scope.row)"
              v-if="detail.status == 2 || detail.status == 1"
            >退款</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      title="发货"
      :visible.sync="shipments.dialog"
      width="50%"
    >
      <el-form
        ref="shipmentsForm"
        :model="shipments.data"
        :rules="shipments.rules"
        style="padding:0 40px"
        label-position="left"
        label-width="80px"
      >
        <el-form-item
          prop="code"
          label="物流公司"
        >
          <el-select
            @change="selectCompany"
            placeholder="请选择物流公司"
            filterable
            v-model="shipments.data.name"
            style="width: 100%;"
          >
            <el-option
              v-for="item in shipments.companyOptions"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />

          </el-select>

        </el-form-item>
        <el-form-item
          prop="orderNum"
          label="物流单号"
        >
          <el-input
            placeholder="请输入物流单号"
            v-model="shipments.data.orderNum"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="click().handleShipmentsCancel('shipmentsForm')">取 消</el-button>
        <el-button
          type="primary"
          @click="click().handleShipmentsClose('shipmentsForm')"
        >确认发货</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="退款"
      :visible.sync="refund.dialog"
      width="50%"
    >
      <el-form
        ref="refundForm"
        :model="refund.data"
        :rules="refund.rules"
        style="padding:0 40px"
        label-position="left"
        label-width="80px"
      >
        <el-form-item
          prop="refundRmb"
          label="退款金额"
        >
          <el-input
            placeholder="请输入退款金额"
            v-model="refund.data.refundRmb"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          prop="reasonDescription"
          label="备注"
        >
          <el-input
            placeholder="请输入"
            v-model="refund.data.reasonDescription"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="click().handleRefundCancel('refundForm')">取 消</el-button>
        <el-button
          type="primary"
          @click="click().handleRefundClose('refundForm')"
        >确认退款</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getOrderDetail,
  getCompanyList,
  sendGoods,
  refundApi,
} from "@/api/merchant-order-manage/order-list";
import loginVue from "../../login.vue";

export default {
  data() {
    var validateRmb = (rule, value, callback) => {
      if (+value > +this.detail.realPayRmb) {
        callback(new Error("退款金额不能大于实付款金额"));
      }
      if (!value) {
        callback(new Error());
      } else {
        callback();
      }
    };
    return {
      loading: false,
      detail: {},
      id: "",
      isPickup: "",
      shipments: {
        dialog: false,
        data: {
          orderNum: "",
          orderId: "",
          goodsId: "",
        },
        // 快递公司
        companyOptions: [],
        rules: {
          // 必填，最多200字
          code: [
            { required: true, message: "请选择物流公司", trigger: "blur" },
          ],
          orderNum: [
            { required: true, message: "请输入物流单号", trigger: "blur" },
          ],
        },
      },
      refund: {
        dialog: false,
        data: {
          refundRmb: "",
          orderId: "",
          reasonDescription: "",
          id: "",
        },

        rules: {
          refundRmb: [
            {
              validator: validateRmb,
              required: true,
              message: "需要填入金额，并且金额不能大于实付款金额",
              trigger: "blur",
            },
          ],
        },
      },
      // 待服务 - 商品信息表格数据
      tableData: [],
    };
  },
  created() {
    this.network().getDetail();
    this.network().getCompany();

    this.isPickup = this.$route.query.state;
  },
  methods: {
    selectCompany(expressCode) {
      const companyData = this.shipments.companyOptions.find(
        (item) => item.code == expressCode
      );
      this.shipments.data = { ...this.shipments.data, ...companyData };
    },
    network() {
      return {
        getDetail: async () => {
          const { uuid } = this.$route.params;
          this.id = uuid;
          this.loading = true;
          try {
            const { data } = await getOrderDetail({ id: uuid });
            this.loading = false;
            this.detail = data;
            console.log(this.detail);
            this.tableData = data.orderGoodsVoList;

            this.tableData.map((item) => {
              item.platformPrice = "¥ " + item.platformPrice;
              item.crossedPrice = "¥ " + item.crossedPrice;
              item.goodsNum = item.platformPrice + " " + item.goodsNum + "件";
            });
          } catch (error) {
            this.loading = false;
          }
        },
        // 获取快递公司
        getCompany: async () => {
          const data = await getCompanyList();
          this.shipments.companyOptions = data.rows;
        },
        // 发货
        sendRequest: async (obj) => {
          const data = await sendGoods(obj);
          if (code == 0) {
            this.shipments.dialog = false;
            this.$message({
              message: "发货成功",
              type: "success",
            });
            this.network().getDetail();
            this.$refs["shipmentsForm"].resetFields();
          }
        },
        // 退款
        refundApi: async (obj) => {
          const { msg, code } = await refundApi(obj);
          if (code == 0) {
            this.refund.dialog = false;
            this.$message.success(msg);
            this.network().getDetail();
            return false;
          }
          return this.$message.error(msg);
        },
      };
    },
    click() {
      return {
        // 发货
        handleShipments: async (row) => {
          this.shipments.data.orderId = row.id;
          this.shipments.data.goodsId = row.goodsId;

          this.shipments.dialog = true;
        },
        // 发货 - 确认 - 关闭对话框
        handleShipmentsClose: async (formName) => {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              let that = this.shipments.data;
              const logistics = {
                orderGoodsRoList: [
                  {
                    orderId: that.orderId,
                    logisticsName: that.name,
                    logisticsNo: that.orderNum,
                    logisticsStatus: "",
                    goodsId: that.goodsId,
                  },
                ],
                orderId: that.orderId,
              };
              this.network().sendRequest(logistics);
            } else {
              return false;
            }
          });
        },
        // 发货 - 取消 - 关闭对话框
        handleShipmentsCancel: async (formName) => {
          this.$refs[formName].resetFields();
          this.shipments.data.name = "";
          this.shipments.dialog = false;
        },

        // 退款
        handleRefund: async (row) => {
          this.refund.data.orderId = row.orderId;
          this.refund.data.id = row.id;
          this.refund.dialog = true;
        },
        // 退款 - 确认 - 关闭对话框
        handleRefundClose: async (formName) => {
          const throttleStatus = this.throttle(); // 节流
          if (!throttleStatus) return;
          this.$refs[formName].validate((valid) => {
            if (valid) {
              let that = this.refund.data;
              const refundInfo = {
                orderGoodsRoList: [
                  {
                    id: that.id,
                    refundRmb: that.refundRmb,
                  },
                ],
                orderId: that.orderId,
                reasonDescription: that.reasonDescription,
              };
              this.network().refundApi(refundInfo);
              this.refund.dialog = false;
            } else {
              return false;
            }
          });
        },
        // 退款 - 取消 - 关闭对话框
        handleRefundCancel: async (formName) => {
          this.refund.dialog = false;
          this.$refs[formName].resetFields();
        },
      };
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  background-color: #f0f2f5 !important;
  padding: 40px;
}

::v-deep {
  .el-descriptions-item__container {
    display: flex;
  }
}
::v-deep .el-form-item__label {
  text-align: right;
}
</style>
  